import functools
import time
import datetime

import requests


def stastics(name):
    def time_logger(func):
        @functools.wraps(func)  # 保留原函数的元数据
        def wrapper(*args, **kwargs):
            start_time = time.time()  # 记录开始时间
            exception_type = None
            try:
                exception = ''
                result = func(*args, **kwargs)  # 执行原函数
                status = 'success'
            except Exception as e:
                result = 0
                exception_type = e
                status = 'failure'
                exception = str(f'{type(e)}: {e}')
            end_time = time.time()  # 记录结束时间
            execution_time = end_time - start_time  # 计算执行时间
            print(f"Function '{func.__name__}' executed in {execution_time:.4f} seconds.")
            print(name)
            url = f'http://10.62.231.140:54250//offline_dataProcess/stastics'
            data = {
                "scripts": name,
                "end_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "duration": round(execution_time, 4),
                "file_count": result,
                "status": status,
                'exception': exception
            }
            try:
                ret = requests.post(url=url, json=data, verify=False, timeout=5)
                print(ret.status_code)
            except Exception as e:
                print(f'统计数据失败：{e}')
                pass
            if exception_type:
                raise exception_type
            return result  # 返回原函数的结果
        return wrapper
    return time_logger

    # 使用方法：
    # @stastics(name='记录层数据提取工具')
    # def work(self):
    #     logger.info(self.input_args)
    #     # self.extra_data_by_process()
    #     self.process_data()
    #     return len(self.input_args['文件路径']) if self.input_args['文件路径'] else 0